package com.feib.soeasy.action;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.Calendar;
import java.util.Date;

import com.feib.soeasy.model.Group;
import com.feib.soeasy.model.Payment;
import com.feib.soeasy.model.UploadFile;
import com.feib.soeasy.pagination.PaginatedList;
import com.feib.soeasy.service.GroupService;
import com.feib.soeasy.service.PaymentService;
import com.feib.soeasy.service.UploadFileService;
import com.feib.soeasy.util.UserUtil;


import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.DontBind;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.StreamingResolution;
import net.sourceforge.stripes.integration.spring.SpringBean;
import net.sourceforge.stripes.validation.DateTypeConverter;
import net.sourceforge.stripes.validation.LocalizableError;
import net.sourceforge.stripes.validation.Validate;
import net.sourceforge.stripes.validation.ValidateNestedProperties;
import net.sourceforge.stripes.validation.ValidationErrorHandler;
import net.sourceforge.stripes.validation.ValidationErrors;

/**
 * @title (#)Soez3002ActionBean.java <br>
 * @description 整批帳單下載 Controller<br>
 * @author Leo Lee
 * @version 1.0.0 2010/12/04
 * @copyright Far Eastern International Bank Copyright (c) 2010<br>
 * @2010/12/04 create by Leo Lee<br>
 */
public class Soez3002ActionBean extends BaseActionBean implements ValidationErrorHandler {

    /**
     * 帳單人工註銷作業作業畫面
     */
    private static final String DEFAULT_JSP = "/WEB-INF/views/soez3002/soez3002.jsp";

    /**
     * 帳單人工註銷作業清單畫面
     */
    private static final String PAYMENT_LIST_JSP = "/WEB-INF/views/soez3002/soez3002List.jsp";
    /**
     * 檔案內容
     */
    private static final String AJAX_QUERY_PAYMENT_JSP = "/WEB-INF/views/soez3002/paymentList.jsp";
    /**
     * 業者代號查詢畫面
     */
    private static final String AJAX_QUERY_GROUP_JSP = "/WEB-INF/views/soez3002/groupPopUpList.jsp";

    /**
     * [業者代號]改變後觸發重製[收款類別]選項結果
     */
    private static final String AJAX_FORMT_DEF_OPTIONS_JSP = "/WEB-INF/views/soez9004/formatDefinitionOptions.jsp";

    /**
     * 帳單業者查詢條件
     */
    private Group qryGroup;

    private Group group;

    private Long uploadFilePk;

    /**
     * 帳單業者查詢結果
     */
    private PaginatedList<Group> queryGroupResult;


    /**
     * 查詢條件
     */
    @ValidateNestedProperties({
        @Validate(field="uploadFilePk", required=true, on={"doAjaxQueryFilePayments"}  )        
        , @Validate(field="group.groupNo", required=true, on={"doAjaxQuery"})
        , @Validate(field="uploadDate", converter=DateTypeConverter.class )
    })
    private UploadFile qryUploadFile;

    /** 
     * 查詢條件-上傳日期起
     */
    @Validate( required=true, on={"doAjaxQuery"}, converter=DateTypeConverter.class)
    private Date qryUploadFrom;

    /**
     * 查詢條件-上傳日期迄
     */
    @Validate( required=true, on={"doAjaxQuery"}, converter=DateTypeConverter.class)
    private Date qryUploadTo;

    @SpringBean("uploadFileService")
    private UploadFileService uploadFileService;

    /**
     * 查詢結果
     */
    private PaginatedList<UploadFile> queryResult;

    /**
     * 查詢單筆Payment
     */
    private Payment resultPayment;


    private String reason;

    @SpringBean("groupService")
    private GroupService groupService;

    /**
     * 檔案帳單明細查詢結果
     */
    private PaginatedList<Payment> queryPaymentResult;


    @SpringBean("paymentService")
    private PaymentService paymentService;

    @DontBind
    @DefaultHandler
    public Resolution doDefault()
    {
        logger.debug("Enter doDefault mehtod.");
        try {
            Calendar cal = Calendar.getInstance();
            qryUploadTo = cal.getTime();
            cal.add(Calendar.MONTH, -1);
            qryUploadFrom = cal.getTime();
        }
        catch (Exception e) {
        }
        return new ForwardResolution(DEFAULT_JSP); 
    }

    /**
     * 查詢
     * @return
     */
    public Resolution doAjaxQuery()
    {
        logger.debug("Enter doAjaxQuery mehtod.");
        try {

            //如果不是銀行端，則查詢條件要加入帳單業者限制
            if (!UserUtil.isBankGroup())
            {
                Group group = new Group();
                group.setGroupPk(UserUtil.getUserGroup().getGroupPk());
                qryUploadFile.setGroup(group);
            }            
            
            // 只查詢已放行資料
            qryUploadFile.setFileStatus(UploadFile.FILE_STATUS_CONFIRM_OK);
            queryResult.setSortDirection(0);           
            queryResult.setPageSize(999);
            //呼叫服務查詢
            queryResult = uploadFileService.queryByUploadFile(
                            qryUploadFile, qryUploadFrom, qryUploadTo, queryResult);


        }
        catch (Exception e) {
            logger.error("帳單人工註銷作業查詢錯誤(Soez3002ActionBean.doAjaxQuery):", e);

            // 轉換錯誤訊息
            ValidationErrors errors = new ValidationErrors();
            errors.addGlobalError(new LocalizableError("doAjaxQuery.exception") );
            getContext().setValidationErrors(errors);
            // 回傳 錯誤 HTML fragments
            return super.errorsToHtmlStreams(errors);
        }

        return new ForwardResolution(PAYMENT_LIST_JSP);
    }

    /**
     * 查詢轉入的帳單資料
     * @return
     */
    public Resolution doAjaxQueryFilePayments()
    {
        logger.debug("Enter doAjaxQueryFilePayments mehtod.");
        try {
            // 設定查詢條件
            Payment payment = new Payment();
            //payment.setGroup(qryUploadFile.getUploadGroup());
            UploadFile uploadFile = new UploadFile();

            uploadFile.setUploadFilePk(qryUploadFile.getUploadFilePk());
            payment.setUploadFile(uploadFile);


            //呼叫服務查詢
            queryPaymentResult = paymentService.queryByPayment(payment, null, null, queryPaymentResult);
            
        }
        catch (Exception e) {
            logger.error("帳單人工註銷作業-帳單內容查詢錯誤(Soez3002ActionBean.doAjaxQueryFilePayments):", e);

            // 轉換錯誤訊息
            ValidationErrors errors = new ValidationErrors();
            errors.addGlobalError(new LocalizableError("doAjaxQuery.exception") );
            getContext().setValidationErrors(errors);
            // 回傳 錯誤 HTML fragments
            return super.errorsToHtmlStreams(errors);
        }

        return new ForwardResolution(AJAX_QUERY_PAYMENT_JSP);
    }

    /**
     * 帳單業者查詢
     * @return
     */
    public Resolution doAjaxQueryGroups()
    {
        logger.debug("Enter doAjaxQueryGroups mehtod.");
        try {
            //如果不是銀行端，則查詢條件要加入帳單業者限制
            if (!UserUtil.isBankGroup())
            {
                throw new Exception("No Authority");
            }


            //USER未輸入查詢條件，所以查詢物件會是NULL(查詢物件不可為NULL)
            if (null == qryGroup)
                qryGroup = new Group();

            //呼叫服務查詢
            queryGroupResult = groupService.queryByGroupExcludeBank(qryGroup, queryGroupResult);
        }
        catch (Exception e) {
            logger.error("帳單上傳記錄查詢-帳單業者查詢錯誤(Soez9004ActionBean.doAjaxQueryGroups):", e);

            // 轉換錯誤訊息
            ValidationErrors errors = new ValidationErrors();
            errors.addGlobalError(new LocalizableError("doAjaxQuery.exception") );
            getContext().setValidationErrors(errors);
            // 回傳 錯誤 HTML fragments
            return super.errorsToHtmlStreams(errors);
        }

        return new ForwardResolution(AJAX_QUERY_GROUP_JSP);
    }


    public Resolution doDownloadUploadFileAction()
    {
        StreamingResolution streamingResolution = null;
        try {
            UploadFile uploadFile = uploadFileService.getUploadFileByPk(uploadFilePk);

            File file = new File(uploadFile.getPdfFilePathOnServer());
            byte[] bytes = new byte[(int)file.length()];

            BufferedInputStream bufferedInputStream = 
                new BufferedInputStream(new FileInputStream(file)); 

            bufferedInputStream.read(bytes);

            ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
            inputStream.close();
            bufferedInputStream.close();

            String isoFileName = new String(uploadFile.getPdfFileName().getBytes(), 
            "ISO8859-1");

            streamingResolution = new StreamingResolution( 
                            "application/pdf",inputStream).setFilename(isoFileName);
        } catch (Exception e) {
            logger.error("帳單下載錯誤(Soez3002ActionBean.doDownloadUploadFileAction):", e);

            // 轉換錯誤訊息
            ValidationErrors errors = new ValidationErrors();
            errors.addGlobalError(new LocalizableError("doDownloadUploadFileAction.exception") );
            getContext().setValidationErrors(errors);
            // 回傳 錯誤 HTML fragments
            return super.errorsToHtmlStreams(errors);
        }

        return streamingResolution;
    }



    public Resolution doAjaxGroupNoChange()
    {
        return new ForwardResolution(AJAX_FORMT_DEF_OPTIONS_JSP);
    }


    public PaginatedList<UploadFile> getQueryResult() {
        return queryResult;
    }



    public void setQueryResult(PaginatedList<UploadFile> queryResult) {
        this.queryResult = queryResult;
    }
    public Payment getResultPayment() {
        return resultPayment;
    }



    public void setResultPayment(Payment resultPayment) {
        this.resultPayment = resultPayment;
    }


    public Long getUploadFilePk() {
        return uploadFilePk;
    }



    public void setUploadFilePk(Long uploadFilePk) {
        this.uploadFilePk = uploadFilePk;
    }



    public UploadFile getQryUploadFile() {
        return qryUploadFile;
    }



    public void setQryUploadFile(UploadFile qryUploadFile) {
        this.qryUploadFile = qryUploadFile;
    }



    public Group getGroup() {
        return group;
    }



    public void setGroup(Group group) {
        this.group = group;
    }

    public Group getQryGroup() {
        return qryGroup;
    }



    public void setQryGroup(Group qryGroup) {
        this.qryGroup = qryGroup;
    }



    public PaginatedList<Group> getQueryGroupResult() {
        return queryGroupResult;
    }



    public void setQueryGroupResult(PaginatedList<Group> queryGroupResult) {
        this.queryGroupResult = queryGroupResult;
    }


    public String getReason() {
        return reason;
    }



    public void setReason(String reason) {
        this.reason = reason;
    }


    public PaginatedList<Payment> getQueryPaymentResult() {
        return queryPaymentResult;
    }



    public void setQueryPaymentResult(PaginatedList<Payment> queryPaymentResult) {
        this.queryPaymentResult = queryPaymentResult;
    }

    
    /**
     * @return the qryUploadFrom
     */
    public Date getQryUploadFrom() {
        return qryUploadFrom;
    }

    
    /**
     * @param qryUploadFrom the qryUploadFrom to set
     */
    public void setQryUploadFrom(Date qryUploadFrom) {
        this.qryUploadFrom = qryUploadFrom;
    }

    
    /**
     * @return the qryUploadTo
     */
    public Date getQryUploadTo() {
        return qryUploadTo;
    }

    
    /**
     * @param qryUploadTo the qryUploadTo to set
     */
    public void setQryUploadTo(Date qryUploadTo) {
        this.qryUploadTo = qryUploadTo;
    }

}
